package servlet;

import model.Blog;
import model.BlogDao;
import model.User;
import model.UserDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2022-03-11
 * Time:9:22
 */
@WebServlet("/blog_detail")
public class BlogDetailServlet extends HttpServlet {

// 当我们需要访问博客详情页的时候，需要在请求中带上参数，具体就得表示出博客的id
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf8");

        User user = Util.checkLogin(req);
        if (user == null){
//            如果当前未登录,就直接重定向到登录页面
            System.out.println("当前未登录不能访问博客详情页！");
            resp.sendRedirect("blog_login.html");
            return;
        }

        //    1.先根据请求中的参数，从数据库中查出指定的博客内容
        String blogId = req.getParameter("blogId");
        if (blogId == null || "".equals(blogId)) {
            String html = "<h3>blogId 为空！</h3>";
            resp.getWriter().write(html);
            return;
        }

        BlogDao blogDao = new BlogDao();
        Blog blog = new Blog();
        blog= blogDao.select(Integer.parseInt(blogId));
        if (blog == null){
           String html = "<h3>指定的博客不存在</h3>";
           resp.getWriter().write(html);
           return;
        }
//在这里，需要根据当前博客的作者 id 查询出对应的作者详细身份
//        把作者的身份信息给渲染到模板中
        UserDao userDao = new UserDao();
        User auhtor = userDao.selectById(blog.getUserId());
        if (auhtor == null){
            String html = "<h3>指定的作者不存在</h3>";
            resp.getWriter().write(html);
            return;
        }
//        Boolean ShowDeleteButton ;
//        if (user.getUserId() == blog.getUserId()){
//            ShowDeleteButton = true;
//        }else {
//            ShowDeleteButton = false;
//        }
        ServletContext context = getServletContext();
        TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
        WebContext webContext = new WebContext(req,resp,getServletContext());
        webContext.setVariable("blog",blog);
        webContext.setVariable("user",auhtor);
//        webContext.setVariable("ShowDeleteButton",ShowDeleteButton);
        webContext.setVariable("ShowDeleteButton",user.getUserId() == auhtor.getUserId());

        engine.process("blog_detail",webContext,resp.getWriter());
    }
}
